<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload files</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<style type="text/css">
	
	.bar {
		width: 300px;
		background: white;
		border: 1px solid gray ;
		float:left;
		height: 10px;		
		display:inline;
		float:left;
		margin-top:5px;
		margin-left:20px;
	}
	
	.progressBar {
		width: 0px;
		height: 100%;
		background: blue;
	}
	.percent{
		display:inline;
	}
	.fileSelector{
		float:left;
	}
	.divActions{
		margin-top:10px;
	}
	.progessPercent{
		visibility:hidden;
	}
</style>

</head>
<body>
	<h1 align="center">Upload multiple files page</h1>
	<h2 align="center">The files will be saved to D:\*</h2>
	<hr align="center" width="30%"/>

	<!-- ------------------------------Main Form------------------------------------ -->
	<div style="padding-left: 200px">
		<form action="/UploadMultipleFiles-3.0/uploadfiles/confirm" method="post" id="uploadForm">
			<div class='divFiles' id="divFiles">
				<!-- use  javascipt to insert html here -->
			</div>
		
			<br/>
			<div class="divActions">
				<input type="button" value="Add another file" id="btnAddMore"/> 
				<input type="button" value="Upload all" id="btnUpload"/> 
			</div>
		</form>
	</div>
	<!-- ------------------------------/Main Form------------------------------------ -->

	<!-- ------------------------------JQuery------------------------------------ -->
	<script>
		
		$(document).ready(function(){
			
			var serverPath = location.pathname;
			
			var  fileCount = 1;
			addMoreFile();
			
			function processUpload(fileInputId){
				if(checkFileSizeLimit(fileInputId)){
					uploadFile(serverPath, fileInputId);
					processUploadingUI(fileInputId);
				}
			}
			
			function checkFileSizeLimit(fileInputId){
				var fileInput = document.getElementById(fileInputId);
				var fileSize = (fileInput.files[0].size/1000/1000).toFixed(2);
				if(fileSize > 200){
					alert("The file's size is " + fileSize + "MB > 200MB, Too large!");
					return false;
				}
				return true;
			}
			
			function processUploadingUI(fileInputId){
				
				var fileInput = document.getElementById(fileInputId);
				var fileName = fileInput.files[0].name;
				var fileSize = (fileInput.files[0].size / 1000 / 1000).toFixed(2);
				
				var hdFileName = $('#' +  fileInputId).parent().find('input[type="hidden"]');
				hdFileName.attr('value', fileName);
				$('#' +  fileInputId).replaceWith("<b>"+ fileName+ "</b>" + " - " + fileSize + " MB");
			} 
			
			function uploadFile(url, fileInputId){
				
				var grand = $('#' + fileInputId).parent().parent();
				var file = document.getElementById(fileInputId).files[0];
				var formData = new FormData();
				formData.append(file.name, file);
				
	            var xhr = new XMLHttpRequest();
	            xhr.open('POST', url, true);
	            xhr.onload = function(e){
	                if (this.status == 200) {
						grand.find('input[id^="btnDelete"]').css('visibility', 'visible');
					}
	            };
	            
				var progressbar = $('#' + fileInputId).parent().parent().find(".progressBar"); 
	            var percent = $('#' + fileInputId).parent().parent().find(".percent");
	            // Listen to the upload progress.
				xhr.upload.onprogress = function(e){
					grand.find('div[class="progessPercent"]').css('visibility', 'visible');
					if (e.lengthComputable) {
						var uploadedPercent = (e.loaded / e.total * 100).toFixed(2) + "%" ;
						progressbar.css("width", uploadedPercent);
						percent.text(uploadedPercent);
					}
				};
	            
	            xhr.send(formData);
			}
	  		
			function addMoreFile(){
				$('#divFiles').append(
					'<div class="divFile">'+
						'<div class="fileSelector">'+
							'<input type="file" id="inpFile' + fileCount + '" name="file"/>'+
							'<input type="hidden" value="" id="hdFileName'+ fileCount + '" name="hdFileName" />'+
						'</div>'+
						'<div class="progessPercent">'+
				            '<div class="bar">'+
				                '<div id="progressBar' + fileCount + '" class="progressBar"></div>'+
				            '</div>'+
							'<div id="percent' + fileCount + '" class="percent" >0%</div>'+
		                    '<input type="button" id="btnDelete' + fileCount + '" value="X" style="visibility:hidden;"/>'+
						'</div>'+
						'<br/>'+
					'</div>'
				);
				fileCount++;
			}
			
			function deleteUploadedFile(url, fileName){
				var xhr = new XMLHttpRequest();
                xhr.open('POST', url, true);
                xhr.onload = function(e){
                    if (this.status == 200) {
                    }
                };
	            xhr.send(fileName);
			}
		
			$(':file').live('change', function() {
				processUpload(this.id);
			});
				
	        document.querySelector('input[type="file"]').addEventListener('change', function(e){
	            processUpload(this.id);
	        }, false);
			
			document.getElementById('btnAddMore').addEventListener('click', function(e){
				addMoreFile();
			}, false);
			
	        $('input[id^="btnDelete"]').live('click', function(){
				
	            // Get <div> element that contains the clicked file field.
	            var divFileField = $(this).parent().parent();
				
				var hdFileName = divFileField.find('input[id^="hdFileName"]');
				deleteUploadedFile(serverPath + "/deletefile", hdFileName.val());
				
	            // Remove the <div> element. 
	            divFileField.remove();
	        });
			
			$('#btnUpload').click(function(e){
				
				$('#uploadForm').submit();
			});
		
		});
	</script>
	<!-- ------------------------------/JQuery------------------------------------ -->
	
</body>
</html>